using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Collections;

namespace FeedBurner.Utility
{
    internal class FeedWriter
    {
        public static string GetFeedXml(Feed feed, bool ContainID, bool ContainUri)
        {
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter);
            xmltextWriter.Formatting = Formatting.Indented;

            xmltextWriter.WriteStartElement("feed");
            if (ContainID)
                xmltextWriter.WriteAttributeString("id", feed.ID.ToString());
            if (ContainUri)
                xmltextWriter.WriteAttributeString("uri", feed.Uri);
            if (feed.Title != null)
                xmltextWriter.WriteAttributeString("title", feed.Title);

            xmltextWriter.WriteStartElement("source");
            if (feed.Url != null)
                xmltextWriter.WriteAttributeString("url", feed.Url);
            xmltextWriter.WriteEndElement();

            if (feed.Services.Count > 0)
            {
                xmltextWriter.WriteStartElement("services");
                foreach (Service service in feed.Services)
                {
                    xmltextWriter.WriteStartElement("service");
                    xmltextWriter.WriteAttributeString("class", service.Name);
                    if (service.Parameters.Count > 0)
                    {
                        foreach (KeyValuePair<string, string> parameter
                            in service.Parameters)
                        {
                            xmltextWriter.WriteStartElement("param");
                            xmltextWriter.WriteAttributeString("name", parameter.Key);
                            if (string.IsNullOrEmpty(parameter.Value))
                                xmltextWriter.WriteValue("");
                            else
                                xmltextWriter.WriteValue(parameter.Value);
                            xmltextWriter.WriteEndElement();
                        }

                    }
                    xmltextWriter.WriteEndElement();
                }
                xmltextWriter.WriteEndElement();
            }

            xmltextWriter.WriteEndElement();
    
            xmltextWriter.Flush();
            xmltextWriter.Close();
            stringWriter.Flush();
                     
            return stringWriter.ToString();
        }  
    }
}
